<template>
  <div class="ql-editor-wrapper ql-editor-wrapperStyle">
    <div class="ql-editor-header">
      <a-icon type="left" style="font-size: 20px" @click="back" />
      <div class="ql-editor-header-title">编辑合同</div>
    </div>
    <div class="ql-editor-content ql-editor-content2">
      <div id="editor-main" class="editor-main">
        <vue-wangeditor ref="editor" v-model="content" :menus="menus" :height="editorHeight" />
      </div>
      <div class="editor-config editor-config2">
        <div class="editor-config-block">
          <div class="editor-config-block-title" style="font-size: 16px">设置模板名称</div>
          <div class="editor-config-block-content">
            <a-input v-model="name" />
          </div>
        </div>
        <div class="editor-config-block">
          <div class="editor-config-block-title" style="font-size: 16px">设置模板变量</div>
          <div class="editor-config-block-content">
            <div class="editor-config-block-content-tip">快速添加员工姓名、部门、岗位等信息，内容中会自动替换为真实信息</div>
            <div v-for="(item, index) in variables" :key="index">
              <div v-if="item.title === '员工个人信息'">
                <div class="editor-config-block-content-title" style="margin-bottom: 8px">{{ item.title }}</div>
                <a-collapse default-active-key="0" :bordered="false" style="background: #fff">
                  <template #expandIcon="props">
                    <a-icon type="caret-right" class="colorIcons" :rotate="props.isActive ? 90 : 0" />
                  </template>
                  <a-collapse-panel :header="item2.name" :style="customStyle" v-for="(item2, index2) in item.children" :key="index2">
                    <div class="editor-config-block-content-tag-wrapper">
                      <div
                        class="editor-config-block-content-tag mb10"
                        v-for="(item3, index3) in item2.val"
                        :key="index3"
                        @click="handleVariable(item3.name)"
                      >
                        {{ item3.name }}
                      </div>
                    </div>
                  </a-collapse-panel>
                </a-collapse>
              </div>
              <div v-else>
                <div class="editor-config-block-content-title">{{ item.title }}</div>
                <div class="editor-config-block-content-tag-wrapper">
                  <div
                    v-for="(tag, idx) in item.children"
                    :key="idx"
                    class="editor-config-block-content-tag"
                    @click="handleVariable(tag.name)"
                  >
                    {{ tag.name }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="ql-editor-footer footerBtn" style="width: 100%; min-width: 1002px">
      <!-- <div class="ql-editor-footer footerBtn" :style="{ width: footerBtnW > 0 ? footerBtnW + 'px' : '0px' }"> -->
      <a-button type="primary" style="margin-right: 12px" @click="updateTemplate"> 设置默认印章位置</a-button>
      <a-button type="primary" @click="saveTemplate"> 仅保存</a-button>
    </div>
  </div>
</template>
<script>
import vueWangeditor from "./vueWangeditor";
import { variableListAll, variableListAll2, templateUpdateReq, templateDetailReq, templateVariablesBatchReq } from "@/api/company/contract";
import { isContainByString } from "@/utils/index";
export default {
  name: "Edit",
  components: {
    vueWangeditor
  },
  data() {
    return {
      isContainByString,
      templateId: null,
      template: null,
      name: "",
      menus: [
        "bold", // 粗体
        "underline", // 下划线
        "italic", // 斜体
        "strikeThrough", // 中线
        "eraser", // 清空格式
        "foreColor", // 文字颜色
        "backColor", // 背景颜色
        "quote", // 引用
        "fontSize", // 字号
        "head", // 标题
        "list", // 无序列表
        "justify", // 有序列表
        "undo", // 撤销
        "redo", // 重做
        "fullscreen"
      ],
      initContent: "",
      content: "",
      options: {},
      cursorPosition: null,
      variables: [],
      variableList: [],
      editorHeight: 0,
      customStyle: "background: #fff;border: 0;overflow: hidden;",
      footerBtnW: 0,
      personalVars: []
    };
  },

  created() {
    this.categoryId = this.$route.params.categoryId;
    this.templateId = this.$route.params.id;
    this.loadTemplate();
    this.loadVaribles();
  },
  mounted() {
    // this.getCursorPosition()
    if (document.getElementById("editor-main")) {
      this.editorHeight = document.getElementById("editor-main").offsetHeight - 40;
    }
    // this.footerBtnW = document.querySelector(".main-content-wrapper").offsetWidth;
    // this.footerBtnW = document.querySelector(".main-contentr").offsetHeight;
  },
  methods: {
    loadVaribles() {
      variableListAll2({ companyId: this.$store.state.hr.companyId })
        // variableListAll()
        .then((res) => {
          const varibles = res.data;
          this.variableList = res.data;
          const jsonArr = [];
          const enterpriseVars = varibles.filter((item) => item.type === "enterprise");
          // const personalVars = varibles.filter(item => item.type === "personal");
          const contractVars = varibles.filter((item) => item.type === "contract");
          // 基本信息
          const basicArr = varibles.filter((item) => item.type === "basic");
          if (basicArr.length > 0) jsonArr.push({ name: "基本信息", val: basicArr });
          // 身份信息
          const empIdCardArr = varibles.filter((item) => item.type === "empIdCard");
          if (empIdCardArr.length > 0) jsonArr.push({ name: "身份信息", val: empIdCardArr });
          // 联系信息
          const contactArr = varibles.filter((item) => item.type === "contact");
          if (contactArr.length > 0) jsonArr.push({ name: "联系信息", val: contactArr });
          // 家庭成员
          const empFamilyArr = varibles.filter((item) => item.type === "empFamily");
          if (empFamilyArr.length > 0) jsonArr.push({ name: "家庭成员", val: empFamilyArr });
          // 紧急联系人
          const empContactsArr = varibles.filter((item) => item.type === "empContacts");
          if (empContactsArr.length > 0) jsonArr.push({ name: "紧急联系人", val: empContactsArr });
          // 教育经历
          const empEducationArr = varibles.filter((item) => item.type === "empEducation");
          if (empEducationArr.length > 0) jsonArr.push({ name: "教育经历", val: empEducationArr });
          this.variables = [
            { title: "企业信息", children: enterpriseVars },
            { title: "员工个人信息", children: jsonArr },
            { title: "合同信息", children: contractVars }
          ];
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
      variableListAll()
        .then((res) => {
          this.personalVars = res.data.filter((item) => item.type === "personal");
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    loadTemplate() {
      templateDetailReq(this.templateId)
        .then((res) => {
          this.template = res.data;
          this.name = this.template.name;
          this.initContent = this.template.content.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&amp;", "&");
          this.content = this.template.content;
          this.$refs.editor.setHtml(this.initContent);
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    saveTemplate() {
      templateUpdateReq(
        Object.assign(this.template, {
          name: this.name,
          content: this.content,
          contentJson: this.content
        })
      )
        .then((res) => {
          this.updateTemplateVariables();
          this.$message.success("合同模板更新成功");
        })
        .catch((err) => {
          console.log("debug log --> ", err);
          this.$message.error("合同模板更新失败");
        });
    },
    updateTemplate() {
      templateUpdateReq(
        Object.assign(this.template, {
          name: this.name,
          content: this.content,
          contentJson: this.content
        })
      )
        .then((res) => {
          this.updateTemplateVariables();
          this.$message.success("默认保存合同模板，正在跳转印章设置");
          this.$router.push(`/${this.isContainByString("contractAdmin") ? "contractAdmin" : "contract"}/type/seal/${this.templateId}`);
        })
        .catch((err) => {
          console.log("debug log --> ", err);
          this.$message.error("合同模板更新失败");
        });
    },
    updateTemplateVariables() {
      // 正则匹配
      // const regex1ARR = this.content.match(/#[A-Za-z0-9\u4e00-\u9fa5]+#/g) || [];
      // const regex2ARR = this.content.match(/#[\u4e00-\u9fa5]+\((.+?)\)+#/g) || [];
      // const regex3ARR = this.content.match(/#.*?#/g) || [];
      const varibleKeys = this.content.match(/#.*?#/g) || [];
      if (varibleKeys && varibleKeys.length > 0) {
        const listTemp = varibleKeys.map((key) => {
          const keyTemp = key.replace(/#/g, "");
          const idx = this.variableList.findIndex((item) => item["name"] === keyTemp);
          const idx2 = this.personalVars.findIndex((item) => item["name"] === keyTemp);
          if (idx > -1) {
            return {
              templateId: this.templateId,
              variableId: this.variableList[idx]["id"],
              necessaryId: this.variableList[idx]["necessaryId"],
              additionalId: this.variableList[idx]["additionalId"],
              personalVarId: idx2 !== -1 ? this.personalVars[idx2]["id"] : null
            };
          }
        });
        const json = { templateId: this.templateId, variableIds: [], necessaryIds: [], additionalIds: [], personalVarIds: [] };
        listTemp.map((item) => {
          if (item) {
            const idx1 = json.variableIds.findIndex((it) => it === item.variableId);
            if (idx1 === -1 && item.variableId) {
              json.variableIds.push(item.variableId);
            }
            const idx2 = json.necessaryIds.findIndex((it) => it === item.necessaryId);
            if (idx2 === -1 && item.necessaryId) {
              json.necessaryIds.push(item.necessaryId);
            }
            const idx3 = json.additionalIds.findIndex((it) => it === item.additionalId);
            if (idx3 === -1 && item.additionalId) {
              json.additionalIds.push(item.additionalId);
            }
            const idx4 = json.personalVarIds.findIndex((it) => it === item.personalVarId);
            if (idx4 === -1 && item.personalVarId) {
              json.personalVarIds.push(item.personalVarId);
            }
          }
        });
        json.variableIds = [...json.variableIds, ...json.personalVarIds];
        delete json.personalVarIds;
        // console.log(json)
        templateVariablesBatchReq(json)
          .then((res) => {})
          .catch((err) => {
            console.log("debug log --> ", err);
          });
      }
    },
    back() {
      this.$router.go(-1);
    },
    handleVariable(text) {
      // this.getCursorPosition()
      this.insertVariable(text);
    },
    getCursorPosition() {
      this.$refs.editor.quill.focus();
      const range = this.$refs.editor.quill.getSelection();
      this.cursorPosition = range.index;
    },
    insertVariable(text) {
      this.$refs.editor.insertHtml("<span>&nbsp;</span>");
      const tempText = `<a style="color: #6A66F6; text-decoration: underline">#${text}#</a>`;
      this.$refs.editor.insertHtml(tempText);
      this.$refs.editor.insertHtml("<span>&nbsp;</span>");
    }
  }
};
</script>
<style lang="scss">
.ql-editor-wrapperStyle {
  .ql-editor-wrapper .editor-main .quill-editor .ql-container .ql-editor {
    height: 600px;
    overflow: auto;
  }

  .ql-editor-content2 {
    width: 100%;
    height: calc(100vh - 164px) !important;
    // min-height: 750px;
    // min-width: 982px;
    padding-right: 0 !important;
  }

  .editor-config2 {
    height: calc(100vh - 228px) !important;
    // min-height: 686px;
  }

  #editor-main {
    width: calc(100% - 332px);
    height: calc(100vh - 228px) !important;
    // min-width: 620px;
    // min-height: 676px;
    overflow: auto;
    margin: 0;
  }
  .ql-editor-header {
    display: flex;
    align-items: center;
    height: 60px;
  }
  .colorIcons {
    color: var(--primary) !important;
  }
  .ant-collapse-header {
    margin-left: -16px;
    padding-left: 32px !important;
    padding-top: 4px !important;
    padding-bottom: 4px !important;
  }
  .ant-collapse-content-box {
    padding: 4px !important;
  }
  .mb10 {
    margin-top: 0 !important;
    margin-bottom: 10px !important;
  }
  .footerBtn {
    position: absolute;
    bottom: 0;
    background: #fff;
    z-index: 20;
  }
}
</style>
